<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="30%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="任务类型: " label-width="100px" prop="taskType">
        <el-select v-model="dataForm.taskType" placeholder="请选择">
          <el-option
            v-for="(item,index) in this.options"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="浏览时间： " prop="browseTaskTime" label-width="100px">
        <el-input type="text" placeholder="按须输入浏览时间" v-model.trim="dataForm.browseTaskTime" maxlength="6" show-word-limit style="width:400px"/>
      </el-form-item>

      <el-form-item label="任务描述： " prop="taskDescription" label-width="100px">
        <el-input type="text" placeholder="请输入奖励描述15字以内" v-model.trim="dataForm.taskDescription" maxlength="15" show-word-limit style="width:400px"/>
      </el-form-item>
      <el-form-item label="奖励描述： " prop="rewardDescription" label-width="100px">
        <el-input type="text" placeholder="请输入内容限制20字以内" v-model.trim="dataForm.rewardDescription" maxlength="20" show-word-limit style="width:400px"/>
      </el-form-item>
      <el-form-item label="奖励积分数量： " prop="rewardNumber" label-width="100px">
        <el-input type="text" placeholder="请输入正整积分数字" v-model.trim="dataForm.rewardNumber" maxlength="6" show-word-limit style="width:400px"/>
      </el-form-item>
      <el-form-item label="类别排序" prop="sort" label-width="100px">
        <el-input type="number" v-model.trim="dataForm.sort" placeholder="限制数字" style="width:80px" />
      </el-form-item>

      <el-form-item label="图标" prop="img">
        <el-upload
          :class="{hide:hideUpload}"
          :action="this.$http.adornUrl(`/task/uploadImg?path=${this.dataForm.taskPath}&token=${this.$cookie.get('token')}`)"
          :limit="1"
          list-type="picture-card"
          :file-list="dataForm.img"
          :before-upload="beforeAvatarUpload"
          :on-preview="handlePreview"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :on-exceed="onExceed"
          style="margin-left: 20px; width: 200px; height: 150px">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
          <img width="100%" height="100px" :src="this.imageUrl" alt="">
        </el-dialog>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        options: [
          {value: '1', label: '商学院阅读'},
          {value: '2', label: '评介订单'},
          {value: '3', label: '浏览新品上架商品'},
          {value: '4', label: '浏览今日必买商品'},
          {value: '5', label: '每日分享'},
          {value: '6', label: '设置头像'},
          {value: '7', label: '设置昵称'},
          {value: '8', label: '浏览新人教程'},
          {value: '9', label: '意见反馈'},
          {value: '10', label: '绑定微信公众号'}
        ],
        hideUpload: false,
        visible: false,
        imageUrl: '',
        dialogVisible: false,
        typeList: [],
        dataForm: {
          id: 0,
          type: '',
          taskType: '1',
          browseTaskTime: null,
          taskDescription: '',
          rewardDescription: '',
          img: [],
          taskPath: 'task',
          taskImg: '',
          enableState: '',
          rewardNumber: ''
        },
        dataRule: {
          /* browseTaskTime: [
            { required: true, message: '浏览时间不能为空', trigger: 'blur' },
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '浏览时间为正整数', trigger: 'blur' }
          ], */
          sort: [
            { required: true, message: '类别排序不能为空', trigger: 'blur' },
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '类别排序为正整数', trigger: 'blur' }
          ],
          taskDescription: [
            { required: false, message: '任务描述不能为空', trigger: 'blur' }
          ],
          rewardDescription: [
            { required: false, message: '奖励描述不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id, type) {
        debugger
        this.hideUpload = false
        this.dataForm.type = type
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          if (this.$refs['dataForm'] !== undefined) {
            debugger
            this.$refs['dataForm'].resetFields()
          }
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/task/getDailyTasksById/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.taskType = data.data.taskType + ''
                this.dataForm.browseTaskTime = data.data.browseTaskTime
                this.dataForm.taskDescription = data.data.taskDescription
                this.dataForm.rewardDescription = data.data.rewardDescription
                if (data.data.taskPath != null && data.data.taskImg != null) {
                  this.dataForm.img.push({name: 'pathKey', url: 'http://image.yilianbaihui.cn/consumer/' + data.data.taskPath + '/' + data.data.taskImg})
                  this.hideUpload = true
                }
                this.dataForm.sort = data.data.sort
                this.dataForm.rewardNumber = data.data.rewardNumber
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        debugger
        console.log(this.dataForm.id)
        if (this.dataForm.img.length > 0) {
          let index = this.dataForm.img[0].url.toString().lastIndexOf('\/')
          this.dataForm.taskImg = this.dataForm.img[0].url.toString().substring(index + 1, this.dataForm.img[0].url.toString().length)
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/task/${!this.dataForm.id ? 'addDailyTasks' : 'modifyDailyTasksById'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'type': this.dataForm.type,
                'browseTaskTime': this.dataForm.browseTaskTime,
                'taskType': this.dataForm.taskType,
                'taskDescription': this.dataForm.taskDescription,
                'rewardDescription': this.dataForm.rewardDescription,
                'taskPath': this.dataForm.taskPath,
                'taskImg': this.dataForm.taskImg,
                'sort': this.dataForm.sort,
                'rewardNumber': this.dataForm.rewardNumber
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshGetDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/gif'
        if (!isJPG) {
          this.$message.error('上传图片只能是  JPG,PNG,GIF 格式！')
        }
      },
      // 图片预览
      handlePreview (file) {
        this.imageUrl = file.url
        this.dialogVisible = true
      },
      // 文件上传成功的钩子函数
      handleSuccess (res, file, fileList) {
        this.hideUpload = fileList.length >= 1
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        debugger
        console.log(res.data)
        if (res.code === 0) {
          this.dataForm.img.push({name: 'pathKey', url: res.data})
        }
      },
      // 删除文件之前的钩子函数
      handleRemove (file, fileList) {
        this.hideUpload = fileList.length >= 1
        for (var i = 0; i < this.dataForm.img.length; i++) {
          var picc = this.dataForm.img[i]
          if (picc.url === file.url) {
            this.dataForm.img.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传1个图片',
          duration: 6000
        })
      }
    }
  }
</script>
